package com.gin.no_gay_alliance.fragment.user.tab;

import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;

import androidx.recyclerview.widget.DividerItemDecoration;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.gin.common.utils.TimeAgo;
import com.gin.common.utils.TimeUtils;
import com.gin.jackson.utils.JacksonUtils;
import com.gin.jackson.utils.ObjectUtils;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.activity.PriMsgActivity;
import com.gin.no_gay_alliance.activity.TopicListActivity;
import com.gin.no_gay_alliance.adpter.user.UserInfoAdapter;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.database.dao.NgaUserInfoDao;
import com.gin.no_gay_alliance.database.entity.NgaUserInfo;
import com.gin.no_gay_alliance.databinding.DialogRecyclerViewBinding;
import com.gin.no_gay_alliance.databinding.FragmentUserCenterTabUserInfo2Binding;
import com.gin.no_gay_alliance.manager.BlockDataManager;
import com.gin.no_gay_alliance.manager.FollowManager;
import com.gin.no_gay_alliance.manager.UserInfoManager;
import com.gin.no_gay_alliance.param.ItemParam;
import com.gin.no_gay_alliance.param.TopicListParam;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.utils.ImageUtils;
import com.gin.no_gay_alliance.utils.PopupMenuUtils;
import com.gin.no_gay_alliance.utils.ViewUtils;
import com.gin.no_gay_alliance.viewmodel.KeyValue;
import com.gin.no_gay_alliance.viewmodel.UserInfoModel;

import java.util.ArrayList;
import java.util.Locale;
import java.util.stream.Collectors;

/**
 * 用户中心 - 基础信息TAB
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/6 17:34
 **/
public class UserInfoTabFragment extends BaseUserCenterTabFragment<FragmentUserCenterTabUserInfo2Binding> implements PopupMenu.OnMenuItemClickListener {

    /**
     * onCreateView 的后续操作
     */
    @Override
    protected void onCreateView() {
        //关注按钮
        configFollowButton();
        // 曾用名按钮
        ViewUtils.setGone(!userInfoModel.usernameChanged, b.btOldName);

        // 头像
        ViewUtils.setGone(ObjectUtils.isEmpty(userInfoModel.avatars), b.ivAvatar, b.tvAvatar);
        if (!ObjectUtils.isEmpty(userInfoModel.avatars)) {
            b.tvAvatar.setText(String.format(Locale.CHINA, "头像(%d)", userInfoModel.avatars.size()));
            Glide.with(requireActivity())
                    //图片网址，或其他来源的图片
                    .load(userInfoModel.avatars.get(0))
                    //图片请求错误时使用的占位图片
                    .error(R.drawable.ic_forum_avatar)
                    // 加载开始时的占位图片
                    .placeholder(R.drawable.ic_forum_avatar)
                    // 缓存转换后的图片
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .into(b.ivAvatar);
        }
        // 用户数据可能不全，从数据库查询补充
        NgaUserInfoDao ngaUserInfoDao = MyApplication.app.ngaDatabase.ngaUserInfoDao();
        // 数据库中的缓存数据
        NgaUserInfo ngaUserInfo = ngaUserInfoDao.get(userInfoModel.userId);
        if (ngaUserInfo != null) {
            // 写入状态数据
            if (userInfoModel.status == null && ngaUserInfo.accountStatus != null) {
                String label = ngaUserInfo.accountStatus.label;
                String ago = TimeAgo.ago(ngaUserInfo.accountStatusTimestamp);
                userInfoModel.status = String.format(Locale.CHINA, "%s (%s)", label, ago);
            }
            // 写入货币数据
            if (userInfoModel.money == null && ngaUserInfo.money != null) {
                userInfoModel.money = String.format(Locale.CHINA,
                        "%d 金 %d 银 %d 铜 (%s)",
                        ngaUserInfo.money.getGold(),
                        ngaUserInfo.money.getSilver(),
                        ngaUserInfo.money.getCopper(),
                        TimeAgo.ago(ngaUserInfo.moneyTimestamp));
            }
        }
        // 点击事件
        ViewUtils.setOnClickListener(this, b.tvPost, b.tvQuery, b.ivAvatar, b.tvAvatar, b.btFollow, b.btOldName);

        // 分割线
        b.recyclerView.addItemDecoration(new DividerItemDecoration(requireActivity(), DividerItemDecoration.VERTICAL));
        b.recyclerView.setAdapter(new UserInfoAdapter(requireActivity(), userInfoModel.toKeyValues()));
    }

    /**
     * 点击事件统一处理
     *
     * @param v 被点击的View
     */
    @Override
    public void onClick(View v) {
        // 关注按钮
        if (v == b.btFollow) {
            FollowManager followManager = MyApplication.app.managerFactory.getFollowManager();
            if (userInfoModel.followed) {
                //取关
                followManager.unfollowUser(userInfoModel.userId, d -> {
                    toast(d.getMessage());
                    userInfoModel.followed = false;
                    configFollowButton();
                });
            } else {
                // 关注
                followManager.followUser(userInfoModel.userId, d -> {
                    toast(d.getMessage());
                    userInfoModel.followed = true;
                    configFollowButton();
                });
            }
        }
        // 曾用名按钮
        if (v == b.btOldName) {
            UserInfoManager manager = MyApplication.app.managerFactory.getUserInfoManager();
            manager.getOldName(userInfoModel.userId, data -> {
                JacksonUtils.printPretty(data);
                ui(() -> {
                    DialogRecyclerViewBinding b = DialogRecyclerViewBinding.inflate(getLayoutInflater());
                    ArrayList<KeyValue> list = data.stream().map(i -> {
                        String key = TimeUtils.format(i.getTime(), TimeUtils.SHORT_FORMATTER) + " 前";
                        return new KeyValue(key, i.getUsername());
                    }).collect(Collectors.toCollection(ArrayList::new));
                    b.recyclerView.setAdapter(new UserInfoAdapter(requireContext(), list));

                    AlertDialogUtils.showMessage(requireContext(), "曾用名", null, b.getRoot()).show();
                });
            });
        }

        // 操作菜单
        if (v == b.tvPost) {
            PopupMenu popupMenu = PopupMenuUtils.create(requireContext(), v, R.menu.user_center_post_menu, this);
            // 判断当前拉黑状态决定显示菜单
            MyApplication.app.managerFactory.getBlockDataManager().blockDataList(false, data -> {
                MenuItem block = popupMenu.getMenu().findItem(R.id.menu_item_block);
                MenuItem unblock = popupMenu.getMenu().findItem(R.id.menu_item_unblock);
                boolean blocked = BlockDataManager.isBlocked(data, userInfoModel.userId);
                ui(() -> {
                    unblock.setVisible(blocked);
                    block.setVisible(!blocked);
                });
            });

            popupMenu.show();
        }
        // 查询菜单
        if (v == b.tvQuery) {
            PopupMenu popupMenu = PopupMenuUtils.create(requireContext(), v, R.menu.user_center_query_menu, this);
            popupMenu.show();
        }
        // 点击头像预览
        if (v == b.ivAvatar || v == b.tvAvatar) {
            ImageUtils.preview(requireActivity(), b.ivAvatar, userInfoModel.avatars, 0);
        }
    }

    /**
     * 点击菜单项事件
     *
     * @param item 被点击的菜单项
     */
    @Override
    public boolean onMenuItemClick(MenuItem item) {

        // 私信
        if (item.getItemId() == R.id.menu_item_pri_msg_new) {
            PriMsgActivity.createPriMsg(requireContext(), handler, userInfoModel.username);
            return true;
        }
        //  使用道具
        if (item.getItemId() == R.id.menu_item_use_item) {
            UserItemTabFragment.showDialog(this, new ItemParam(userInfoModel.userId));
            return true;
        }
        //  拉黑
        if (item.getItemId() == R.id.menu_item_block) {
            MyApplication.app.managerFactory.getBlockDataManager().block(userInfoModel.userId);
            return true;
        }
        //  取消拉黑
        if (item.getItemId() == R.id.menu_item_unblock) {
            MyApplication.app.managerFactory.getBlockDataManager().unblock(userInfoModel.userId);
            return true;
        }
        // 用户主题
        if (item.getItemId() == R.id.menu_item_user_topic) {
            TopicListParam param = TopicListParam.userTopic(userInfoModel.userId, false, null);
            TopicListActivity.startActivity(requireContext(), param);
            return true;
        }
        // 用户回复
        if (item.getItemId() == R.id.menu_item_user_reply) {
            TopicListParam param = TopicListParam.userReply(userInfoModel.userId, null);
            TopicListActivity.startActivity(requireContext(), param);
            return true;
        }
        // 用户收藏
        if (item.getItemId() == R.id.menu_item_user_favor) {
            TopicListParam param = new TopicListParam();
            param.type = TopicListParam.Type.FAVOR;
            param.authorUid = userInfoModel.userId;
            TopicListActivity.startActivity(requireContext(), param);
            return true;
        }
        return false;
    }

    private void configFollowButton() {
        ui(() -> {
            b.btFollow.setText(userInfoModel.followed ? R.string.followed : R.string.follow);
            ViewUtils.setGone(userInfoModel.userId == MyApplication.getClient().getUserId(), b.btFollow);
        });
    }


    /**
     * 实例化
     *
     * @param userInfoModel 用户信息
     * @return Fragment
     */
    public static UserInfoTabFragment newInstance(UserInfoModel userInfoModel) {
        UserInfoTabFragment fragment = new UserInfoTabFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_USER_INFO, userInfoModel);
        fragment.setArguments(args);
        return fragment;
    }
}
